<?php

namespace App\Remote\Mybank;

use App\Console\Commands\Mybank\RmsOrderBillPayCommand;
use App\Exceptions\BaseException;
use App\Kuafu\Mybank\Enum\MybankFunctionEnum;
use App\Kuafu\Mybank\Model\MybankBatchNoRecordModel;
use App\Kuafu\Mybank\Model\MybankBillRecordModel;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MybankCreateBatchRemote extends Remote
{

    /**
     * 对账文件上传
     * @param string $acquireId
     * @param string $batchNo
     * @param string $batchDate
     * @param string $merchantId
     * @param array $data
     * @param int $source
     * @param array $fuyouBillRecordDate
     * @return bool
     */
    public static function batchFileUpload(
        string $acquireId,
        string $batchNo,
        string $batchDate,
        string $merchantId,
        array $data,
        int $source,
        array $fuyouBillRecordDate = []
    ): bool {
        $filePath       = Remote::getIsvOrgId() . '/' . $acquireId . '/' . $batchNo . '/';
        $detailFileName = 'merchant_trade_detail_' . $batchNo . '.txt';
        $finishFileName = 'finish_' . $batchNo . '.txt';

        //交易明细文件/upload/${isvOrgId}/${acquireId}/${batchNo}/merchant_trade_detail_${batchNo}.txt
        //明细标档文件：/upload/${isvOrgId}/${acquireId}/${batchNo}/finish_${batchNo}.txt
        $tempData = $data;
        if ($source == MybankBillRecordModel::SOURCE_CANTEEN && $fuyouBillRecordDate) {
            $tempData = $fuyouBillRecordDate;
        }
        $detailContent = <<<STR
渠道类型,交易类型,批次号,对账日,网商订单号,isv支付单号,渠道支付单号,isv退款单号,渠道退款单号,交易总金额,实际金额,渠道手续费,币种,用户标识,商户号,交易状态,备注,创单时间,交易时间,收单机构编号
STR;

        $str        = "";
        $createData = [];
        foreach ($tempData as $v) {
            if ($source == MybankBillRecordModel::SOURCE_CANTEEN && $fuyouBillRecordDate) {//堂食订单
                $channelType      = (new RmsOrderBillPayCommand)->switchChannelType($v['transactionType']);
                $mybankOrderNo    = $v['mybankOrderNo'];//网商订单号
                $outTradeNo       = $v['merchantOrderNo'];//isv支付单号
                $channelTradeNo   = $v['channelOrderNo'];//渠道支付单号
                $tradeAmount      = $v['transactionAmount'];//交易总金额
                $transDate        = $v['transactionCompletionTime'];//交易时间
                $channelFeeAmount = $v['transactionFee'];//手续费
                $channelType      = !empty($channelType) ? $channelType : 'ALIPAY';//渠道类型
                $merchantId       = $v['mybankMerchantId'];//网商商户号
            } else {
                $mybankOrderNo    = '';//网商订单号
                $outTradeNo       = $v['transId'];//isv支付单号
                $channelTradeNo   = $v['transId'];//渠道支付单号
                $tradeAmount      = $v['transAmount'];//交易总金额
                $transDate        = $v['transDate'];//交易时间
                $channelFeeAmount = 0;//手续费
                $channelType      = 'ALLINPAY';//渠道类型
            }
            if (isset($v['merchantId']) && $v['merchantId']) {
                $merchantId = $v['merchantId'];
            }
            $actualAmount = $tradeAmount - $channelFeeAmount;//实际金额 交易总金额 = 实际金额 + 渠道手续费
            $arr          = [
                $channelType,                                                                  // 渠道类型,
                "SINGLE_PAY",                                                                  // 交易类型,
                $batchNo,                                                                      // 批次号,
                $batchDate,                                                                    // 对账日,
                $mybankOrderNo,                                                                // 网商订单号,
                $outTradeNo,                                                                   // isv支付单号,
                $channelTradeNo,                                                               // 渠道支付单号,
                '',                                                                            // isv退款单号,
                '',                                                                            // 渠道退款单号,
                bcdiv100($tradeAmount),                                                        // 交易总金额
                bcdiv100($actualAmount),                                                       // 实际金额,
                bcdiv100($channelFeeAmount),                                                   // 渠道手续费,
                '156',                                                                         // 币种,
                '',                                                                            // 用户标识,
                $merchantId,                                                                   // 商户号,
                'SUCCESS',                                                                     // 交易状态,
                '',                                                                            // 备注,
                date('YmdHis', $transDate),                                             // 创单时间,
                date('YmdHis', $transDate),                                             // 交易时间,
                $acquireId,                                                                    // 收单机构编号
            ];

            $str          .= implode(',', $arr) . PHP_EOL;
            $createData[] = [
                'channelType'      => $channelType,
                'tradeType'        => "SINGLE_PAY",
                'batchNo'          => $batchNo,
                'reconDt'          => $batchDate,
                'mybankOrderNo'    => $mybankOrderNo,
                'outTradeNo'       => $outTradeNo,
                'channelTradeNo'   => $channelTradeNo,
                'outRefundNo'      => "",
                'channelRefundNo'  => "",
                'tradeAmount'      => $tradeAmount,
                'actualAmount'     => $actualAmount,
                'channelFeeAmount' => $channelFeeAmount,
                'ccy'              => "156",
                'userId'           => "",
                'merchantId'       => $merchantId,
                'status'           => "SUCCESS",
                'remark'           => "",
                'createTime'       => $transDate,
                'tradeTime'        => $transDate,
                'acquireId'        => $acquireId,
                'createdAt'        => time(),
                'type'             => $source,
                'billRecordId'     => $v['id'],//三方账单id
            ];
        }

        $detailContent .= PHP_EOL . $str;

        $detailUploadStatus = Storage::disk('mybank-sftp')->put($filePath . $detailFileName, $detailContent);
        $finishUploadStatus = Storage::disk('mybank-sftp')->put($filePath . $finishFileName, "");

        if ($createData) {
            collect($createData)->chunk(500)->each(function ($item) {
                $insertData = $item->toArray();
                $insertData = array_values($insertData);
                MybankBatchNoRecordModel::createData($insertData);
            });
        }
        return true;
    }


    /**
     * 创建批次接口
     * 外卖
     * BILL_STMT_AVAILABLE_SHARE -- ISV收单，结算至余额(未提前创单)
     * BATCH_CREATE_ORDER_STMT_AVAILABLE_FREEZE -- ISV收单，结算至余额并冻结(未提前创单)
     * STMT_AVAILABLE_SUM_SHARE -- ISV收单，结算至余额并分账（汇总分账）
     * 堂食
     * STMT_AVAILABLE_SUM_SHARE -- ISV收单，结算至余额并分账（汇总分账）
     * STMT_AVAILABLE_FREEZE_SUM_WITHHOLD-- ISV收单，结算至余额冻结并分账（汇总分账）
     * @param string $batchNo
     * @param int $source
     * @return mixed
     * @throws BaseException
     * @throws GuzzleException
     */
    public static function batchCreate(string $batchNo, int $source)
    {
        $batchType = 'BATCH_CREATE_ORDER_STMT_AVAILABLE_FREEZE';
        if ($source == MybankBillRecordModel::SOURCE_CANTEEN) {
            $batchType = 'STMT_AVAILABLE_FREEZE_SUM_WITHHOLD';
        }
        $params = [
            'IsvOrgId'       => Remote::getIsvOrgId(),
            'BatchNo'        => $batchNo,
            'AcquireId'      => 'DEFAULT',
            'BatchType'      => $batchType,
            'FileUploadType' => 'SFTP'
        ];
        return self::customRequestV2(
            config('pay.mybank.bkServerUrl'),
            Request::METHOD_POST,
            self::buildXmlRequestData($params, MybankFunctionEnum::BKCLOUDBATCH_BATCH_CREATE)
        );
    }


    /**
     * 批次查询接口
     * @param string $batchInstanceId
     * @param string $batchNo
     * @return mixed
     * @throws GuzzleException|BaseException
     */
    public static function batchQuery(string $batchInstanceId, string $batchNo)
    {
        $params = [
            'IsvOrgId'        => Remote::getIsvOrgId(),
            'BatchNo'         => $batchNo,
            'BatchInstanceId' => $batchInstanceId,
            'AcquireId'       => 'DEFAULT'
        ];
        return self::customRequestV2(
            config('pay.mybank.bkServerUrl'),
            Request::METHOD_POST,
            self::buildXmlRequestData($params, MybankFunctionEnum::BKCLOUDBATCH_BATCH_QUERY)
        );
    }


    /**
     * 网商预创订单
     */
    public static function bkCloudfundsBillPay(
        string $merchantId,
        string $kfOrderId,
        int $totalAmount,
        string $channelType
    ) {
        $params = [
            'IsvOrgId'        => Remote::getIsvOrgId(),
            'PayeeMerchantId' => $merchantId,
            'OutTradeNo'      => $kfOrderId,
            'TotalAmount'     => $totalAmount,
            'Currency'        => 'CNY',
            'TradeType'       => 'SINGLE_PAY',
            'ChannelType'     => $channelType,
            'Body'            => '夸父炸串-炸串',
        ];
        return self::returnBodyData(self::customRequestV2(
            config('pay.mybank.sbServerUrl'),
            Request::METHOD_POST,
            self::buildXmlRequestData($params, MybankFunctionEnum::BKCLOUDFUNDS_BILL_PAY)
        ));
    }
}
